package returnBook;

import getData.GetDate;
import libraryRun.MainFrame;
import mySQLServer.Link;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ReturnBook extends JFrame {
    private ReturnBook myReturnBook;
    public int sum;
    public ReturnBook(){
        super("图书归还界面");
        myReturnBook=this;
    }

    public void returnBook(MainFrame myJFrame){
        setLayout(null);
        Container container=this.getContentPane();
        setSize(1200,650);

        //面板
        JPanel p1=new JPanel(new FlowLayout(FlowLayout.CENTER));
        JPanel p2=new JPanel(new FlowLayout(FlowLayout.CENTER,20,20));
        JPanel p3=new JPanel(new BorderLayout());

        //文本行
        JTextField field1=new JTextField(15);
        JTextField field2=new JTextField(15);

        //按钮
        JButton button1=new JButton("归 还");
        JButton button2=new JButton("取 消");

        //标签
        JLabel label=new JLabel("图 书 归 还");
        JLabel label1=new JLabel("图 书 名");
        JLabel label2=new JLabel("图 书 Id");

        //表格
        String[] tableHeader={"用户名","用户Id","借阅书名","借阅书号","借阅时间","归还时间"};
        Object[][] tableData=new Object[50][6];
        JTable jTable=new JTable(tableData,tableHeader);

        //滚动框
        JScrollPane jScrollPane=new JScrollPane(jTable);

        //颜色
        Color color1=new Color(203, 26, 40);
        Color color2=new Color(87, 78, 64, 116);
        Color color3=new Color(7, 124, 161, 255);
        Color color4=new Color(13, 50, 197,225);

        //字体
        Font font1=new Font("宋体",Font.BOLD,45);
        Font font2=new Font("宋体",Font.BOLD,30);
        Font font3=new Font("宋体",Font.BOLD,17);
        Font font4=new Font("宋体",Font.BOLD,15);
        Font font5=new Font("宋体",Font.BOLD,14);


        //设置字体
        label.setFont(font1);
        label1.setFont(font2);
        label2.setFont(font2);
        field1.setFont(font3);
        field2.setFont(font3);

        //设置位置
        p1.setBounds(220,20,750,120);
        p2.setBounds(180,250,430,150);
        p3.setBounds(630,220,480,200);

        //设置大小
        label.setPreferredSize(new Dimension(700,120));
        label1.setPreferredSize(new Dimension(180,30));
        label2.setPreferredSize(new Dimension(180,30));
        button1.setPreferredSize(new Dimension(100,30));
        button2.setPreferredSize(new Dimension(100,30));

        //设置对其方式
        label.setHorizontalAlignment(JLabel.CENTER);

        //表头设置
        jTable.getTableHeader().setResizingAllowed(false); //用户不可以通过拖拉表头间调整各列大小
        jTable.getTableHeader().setReorderingAllowed(false); //用户不可以通过拖动表头以重新排列各列
        jTable.getTableHeader().setFont(font4);
        jTable.getTableHeader().setForeground(color1);

        //表格设置
        jTable.setRowHeight(20); //设置行高
        jTable.setFont(font5);
        jTable.setForeground(color4);
        jTable.setSelectionForeground(color3); //设置被选中的行前景(字体颜色)
        jTable.setSelectionBackground(color2); //设置被选中的行背景
        jTable.getColumnModel().getColumn(1).setPreferredWidth(50); //先获取到某列返回一个TableCoumn 设置列宽
        jTable.getColumnModel().getColumn(3).setPreferredWidth(55);


        //注册监听器
        ImageIcon imageIcon1=new ImageIcon("icon/imageIcon6.jpg");
        imageIcon1.setImage(imageIcon1.getImage().getScaledInstance(50,45,Image.SCALE_AREA_AVERAGING));
        button1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(field1.getText().equals("")||field2.getText().equals("")){
                    JOptionPane.showMessageDialog(myReturnBook,"请输入完整图书信息","输入确认",1,imageIcon1);
                    return;
                }
                if(JOptionPane.showConfirmDialog(myReturnBook,"确认归还吗？","确认归还",JOptionPane.YES_NO_CANCEL_OPTION,1,imageIcon1)==0){
                    Link link=new Link();
                    try {
                        Connection con=link.linkDatebase();
                        String sql="select * from [books] where bookId="+field2.getText()+" and bookName='"+field1.getText()+"'";
                        String sql1="update [book_user] set returnedDate='"+ GetDate.getTime()+"' where bookId="+field2.getText();
                        int result=search(con,field2.getText(),myJFrame.getUserId(),sql,sql1);
                        if(result==0){
                            JOptionPane.showMessageDialog(myReturnBook,"bookName和bookId不匹配！","信息匹配",1,imageIcon1);
                        }else if(result==1){
                            JOptionPane.showMessageDialog(myReturnBook,"用户与书籍信息不匹配！","信息匹配",1,imageIcon1);
                        }else if(result==3){
                            JOptionPane.showMessageDialog(myReturnBook,"归还成功！","确认归还",1,imageIcon1);
                        }
                        else{
                            JOptionPane.showMessageDialog(myReturnBook,"该书籍已归还！","信息匹配",1,imageIcon1);
                        }
                        sql="select * from [book_user] where userId='"+myJFrame.getUserId()+"'";
                        showInTable(con,jTable,sql);
                        link.closeDatebase(con);
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    } catch (ClassNotFoundException classNotFoundException) {
                        classNotFoundException.printStackTrace();
                    }
                }
            }
        });

        button2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                myJFrame.setVisible(true);
                dispose();
            }
        });

        myReturnBook.addWindowListener(new WindowAdapter() {

            public void windowOpened(WindowEvent e) {
                Link link=new Link();
                try {
                    Connection con=link.linkDatebase();
                    String sql="select * from [book_user] where userId='"+myJFrame.getUserId()+"'";
                    showInTable(con,jTable,sql);
                    link.closeDatebase(con);
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                } catch (ClassNotFoundException classNotFoundException) {
                    classNotFoundException.printStackTrace();
                }
            }

            public void windowClosing(WindowEvent e) {
                myJFrame.setVisible(true);
            }
        });

        //放入面板
        p1.add(label);

        p2.add(label1);
        p2.add(field1);
        p2.add(label2);
        p2.add(field2);
        p2.add(button1);
        p2.add(button2);

        p3.add(jScrollPane);

        //放入容器
        container.add(p1);
        container.add(p2);
        container.add(p3);

        setIconImage((new ImageIcon("icon/imageIcon5.jpg")).getImage());
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(false);
        setVisible(true);
    }

    public int search(Connection con, String bookId,String userId, String sql, String sql1) throws ClassNotFoundException, SQLException {
        int flag=0;
        int remainedCount=0;
        String lendDate="";
        Statement stmt=con.createStatement();
        Statement stmt1=con.createStatement();
        ResultSet rs=stmt.executeQuery(sql);
        if(rs.next()){
            flag=1;
            remainedCount=rs.getInt("remainedCount")+1;
            sql="select * from [book_user] where bookId="+bookId+" and userId='"+userId+"'";
            ResultSet rs1=stmt1.executeQuery(sql);
            while(rs1.next()){
                flag=2;
                if("0".equals(rs1.getString("returnedDate"))){
                    flag=3;
                    lendDate=rs1.getString("borrowDate");
                    break;
                }
            }
        }
        if(flag==3){
            sql="update [books] set remainedCount="+remainedCount+" where bookId="+bookId;
            sql1=sql1+" and borrowDate='"+lendDate+"'";
            stmt.executeUpdate(sql);
            stmt.executeUpdate(sql1);
        }
        return flag;
    }

    public void showInTable(Connection con,JTable jTable,String sql) throws SQLException{
        sum=0;
        Statement stmt=con.createStatement();
        ResultSet rs=stmt.executeQuery(sql);
        while (rs.next()){
            jTable.getModel().setValueAt(rs.getString("userName"),sum,0);
            jTable.getModel().setValueAt(rs.getString("userId"),sum,1);
            jTable.getModel().setValueAt(rs.getString("bookName"),sum,2);
            jTable.getModel().setValueAt(rs.getString("bookId"),sum,3);
            jTable.getModel().setValueAt(rs.getString("borrowDate"),sum,4);
            if(rs.getString("returnedDate").equals("0"))
                jTable.getModel().setValueAt("",sum,5);
            else
                jTable.getModel().setValueAt(rs.getString("returnedDate"),sum,5);
            sum++;
        }
    }

}
